

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class LogExplorerPage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() => LogExplorerPageState();
}

Future<File> getLogFile() async {
  return File("${(await getApplicationDocumentsDirectory()).path}/errors.log");
}

class LogExplorerPageState extends State<LogExplorerPage> {
  var logs = <String>[];

  Future<void> loadLogs() async {

    var ERROR_LOG_FILE = await getLogFile();

    if (!ERROR_LOG_FILE.existsSync()){
      ERROR_LOG_FILE.createSync();
    }
    logs = (await ERROR_LOG_FILE.readAsLines()).reversed.toList();
    setState(() {

    });
  }

  @override
  void initState() {
    loadLogs();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Log Explorer"),
        centerTitle: true,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.clear),
            onPressed: () async {
              var ERROR_LOG_FILE = await getLogFile();
              print(ERROR_LOG_FILE.path);
              if(ERROR_LOG_FILE.existsSync()) await ERROR_LOG_FILE.delete();
              await loadLogs();
            },
          )
        ],
      ),
        body: ListView(
          children: logs.map((log) => ListTile(
            title: Text(log),
          )).toList()
        )
    );
  }
}